import { $, updateFloat } from "../../utils";


export abstract class Action {
    weight: number;
    abstract run(): any;
}

export class ClickAction extends Action {
    weight: number = 10;
    target: UiObject;
    constructor(target: UiObject) {
        super();
        this.target = target;
    }
    run() {
        $.tryClickButton(this.target)
    }
}
/**
 * 上划
 */
export class SwipeUpAction extends Action {
    weight: number = 8;
    run() {
        $.swipeUp()
        sleep(3000)
    }
}
/**
 * f返回
 */
export class BackAction extends Action {
    weight: number = 9;
    run() {
        back()
        sleep(3000)
    }
}


/**
 * 回到首页
 */
export class ToShouYeAction extends Action {
    packageName: string;
    constructor(packageName: string) {
        super();
        this.packageName = packageName;
    }
    run() {
        let hasShouYe = selector().descMatches(/首页|精选|我|消息/).visibleToUser(true).findOne(3000)
        while (!hasShouYe) {
            if ($.getCurrentPackage() !== this.packageName) {
                return false;
            }
            hasShouYe = selector().descMatches(/首页|精选|我|消息/).visibleToUser(true).findOne(3000)
            if (!hasShouYe) {
                back();
                sleep(3000)
                $.tryClickButton(selector().textMatches(/退出直播间|退出/).visibleToUser(true).findOne(3000))
                log(`没有找到首页`)
            }
        }
        return true;
    }
}

export class ToLiveRoomAction extends Action {
    packageName: string;
    constructor(packageName: string) {
        super();
        this.packageName = packageName;
    }
    run() {
        let hasShouYe = selector().idMatches(/.*?live_audience_count_text/).visibleToUser(true).findOne(3000)
        while (!hasShouYe) {
            if ($.getCurrentPackage() !== this.packageName) {
                return false;
            }
            hasShouYe = selector().idMatches(/.*?live_audience_count_text/).visibleToUser(true).findOne(3000)
            if (!hasShouYe) {
                back();
                sleep(3000)
            }
        }
        return true;
    }
}

export class WaitRedOpenAction extends Action {
    run() {
        selector().textMatches(/.*?秒后开奖/).waitFor()
        let node = selector().textMatches(/.*?秒后开奖/).findOne()
        const text = node.text();
        let total = 0;
        if (text) {
            const res = text.match(/(\d+)秒后开奖/)
            if (res && res.length > 0) {
                let [, time] = res;
                console.log({ time })
                total = parseInt(time);
            }
        }
        while (total > 0) {
            total -= 1;
            updateFloat({ currentResult: `等待开奖${total}s` })
            sleep(1000)
        }
        let leave = 10;
        while (leave > 0) {
            leave -= 1;
            updateFloat({ currentResult: `${leave}s后离开直播间` })
            sleep(1000)
        }
        /**
         * todo 查询中i将结果
         */
        return true;
    }
}

export class ClickLeftMenuAction extends Action {
    packageName: string;
    constructor(packageName: string) {
        super();
        this.packageName = packageName;
    }
    run(): void {
        // 回到首页
        new ToShouYeAction(this.packageName).run()
        // 点击左侧按钮
        const leftBtn = selector().idEndsWith('left_btn').visibleToUser(true).findOne()
        const mineMoneyButton = selector().text('我的钱包').visibleToUser(true).findOne(3000)
        while (!mineMoneyButton) {
            $.tryClickButtonUtil(leftBtn)
        }
    }
}

export class ClickAndBackAction extends Action {
    target: UiObject;
    constructor(target: UiObject) {
        super();
        this.target = target;
    }
    run() {
        $.tryClickButton(this.target)
        back()
        sleep(3000)
    }
}

export class OpenMineMoneyAction extends Action {
    packageName: string;
    constructor(packageName: string) {
        super();
        this.packageName = packageName;
    }
    run(): void {
        // 回到首页
        new ToShouYeAction(this.packageName).run()
        updateFloat({ tip: `成功进入首页，正在查找左侧菜单按钮` })
        // 点击左侧按钮
        if (!$.tryClickButton(selector().idEndsWith('left_btn').visibleToUser(true).findOne(15 * 1000))) {
            this.run();
            return;
        }
        if (!selector().text('我的钱包').visibleToUser(true).findOne(15 * 1000)) {
            this.run();
            return;
        }
        updateFloat({ tip: `找到左侧菜单按钮，正在查找我的钱包按钮` })
        if (!$.tryClickButton(selector().text('我的钱包').visibleToUser(true).findOne(15 * 1000))) {
            this.run();
            return;
        }
        updateFloat({ tip: `正在进入我的钱包页面` })
    }
}

export class GetMineMoneyAction extends Action {
    packageName: string;
    constructor(packageName: string) {
        super();
        this.packageName = packageName;
    }
    private getTexts() {
        let textNodes = textMatches(/.{1,10}/).visibleToUser(true).find()
        while (textNodes.length <= 0) {
            textNodes = textMatches(/.{1,10}/).visibleToUser(true).find()
            updateFloat({ tip: `页面加载中...` })
            sleep(1000)
        }
        return textNodes;
    }
    run(): void {
        // 回到首页
        new OpenMineMoneyAction(this.packageName).run()
        // 点击左侧按钮
        updateFloat({ tip: `尝试获取余额` })
        let textNodes = this.getTexts()
        let texts = textNodes.map(node => node.text()).join(' ')
        let res = texts.match(/快币\(充值\)\s(\d+)/)
        while (!(res && res.length > 0)) {
            let clickNode: UiObject;
            textNodes.map(node => {
                const text = node.text();
                if (text === '立即领取') {
                    new ClickAndBackAction(node).run()
                }
                if (text === '去看看') {
                    new ClickAndBackAction(node).run()
                }
                return true;
            });
            if (!clickNode) {
                updateFloat({ tip: textNodes.map(node => node.text()).join(` `) })
            }
            textNodes = this.getTexts()
            texts = textNodes.map(node => node.text()).join(' ')
            res = texts.match(/快币\(充值\)\s(\d+)/)
        }
        const [, money] = res;
        if (this.packageName === $.PACKAGES["com.kuaishou.nebula"]) {
            updateFloat({ nebulaCurrentMoney: money, currentResult: `查询成功`, tip: `` });
        }
        if (this.packageName === $.PACKAGES["com.smile.gifmaker"]) {
            updateFloat({ kwaiCurrentMoney: money, currentResult: `查询成功`, tip: `` });
        }
        new ToShouYeAction(this.packageName).run()
    }
}

export class OpenLiveRoomAction extends Action {
    liveStreamId: string;
    constructor(liveStreamId: string) {
        super();
        this.liveStreamId = liveStreamId;
    }
    run() {
        let flag: any = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK;
        const uri = `kwai://live/play/${this.liveStreamId}`;
        const intent = app.intent({
            action: "android.intent.action.VIEW",
            data: uri,
            flags: flag
        });
        context.startActivity(intent);
        sleep(3000)
    }
}